<script lang="ts" setup>
import { onUnmounted, reactive, ref, toRefs, unref, watchEffect, computed } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { filterOptionDict } from "@/utils/filters";
import { useDict } from "@/hooks/useDict";
import { Edit, Plus } from "@element-plus/icons-vue";
import { cloneDeep } from "lodash-es";
import { add, edit } from "@/api/menu";
import { useFileUpload } from "@/hooks/useFileUpload";
interface Props {
  id?: IDType;
  type: DialogType;
  updateData?: MenuBack;
  treeData: MenuBack[];
  pid?: number;
}
const props = withDefaults(defineProps<Props>(), {});
const emits = defineEmits(["getList", "update:modelValue"]);
const { handleUpload, files, uploadFile } = useFileUpload();
const { type } = toRefs(props);
const { getDictList } = useDict();
const dictObj = getDictList(["systemid"]);
const visibleIcon = ref(false);
const initForm: MenuBack = {
  name: "",
  title: "",
  parentId: undefined,
  path: "",
  remark: "",
  component: "",
  redirect: "",
  icon: "",
  type: 2,
  sortNumber: 10,
};

const ruleFormRef = ref<FormInstance>();
const ruleForm = ref<MenuBack>();
const propsTree = {
  checkStrictly: true,
  label: "title",
  value: "id",
  emitPath: false,
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入别名", trigger: "blur" }],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  path: [{ required: true, message: "请输入路径/标识", trigger: "blur" }],
});
const loading = ref<boolean>(false);
const types = computed(() => {
  return ruleForm.value?.type;
});

const isMene = computed(() => {
  return ruleForm.value && ruleForm.value.type === 2;
});
const isBtn = computed(() => {
  return ruleForm.value && ruleForm.value.type === 1;
});

const watchId = watchEffect(() => {
  if (type.value !== "create") {
    ruleForm.value = cloneDeep(props.updateData);
  } else {
    ruleForm.value = Object.assign({}, initForm);
    ruleForm.value.parentId = props.pid;
  }
});
onUnmounted(() => {
  watchId();
});
const subLoading = ref(false);
const submitForm = async () => {
  if (type.value === "view") return handleClose();
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (!valid) return;
    const { children, ...arg } = ruleForm.value!;
    const ruleForms = Object.assign({}, arg);
    let functions: Function;

    functions = type.value === "create" ? add : edit;
    subLoading.value = true;
    functions(ruleForms)
      .then((res) => {
        ElMessage.success("添加成功");
        emits("getList");
        handleClose();
      })
      .catch(() => {
        subLoading.value = false;
      });
  });
};
const handleClose = () => {
  emits("update:modelValue");
};

const handleChange = () => {};

const handleBlur = () => {
  console.log(ruleForm.value?.name);
  if (!ruleForm.value) return;
  if (ruleForm.value.name) {
    if (!ruleForm.value.path) {
      ruleForm.value.path = ruleForm.value.name.toLowerCase();
    }
    if (!ruleForm.value.icon) {
      ruleForm.value.icon = ruleForm.value.name.toLowerCase();
    }
  }
};

const handleIcon = () => {
  visibleIcon.value = true;
};
const changeIcon = (icon: string) => {
  ruleForm.value.icon = icon;
};

const handleUploads = () => {
  handleUpload({ accept: "image/*" }).then((file) => {
    uploadFile(file).then((res) => {
      ruleForm.value.icon = res.id;
    });
  });
};

defineExpose({
  submitForm,
});
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    v-if="ruleForm"
    class="ruleForm"
    :close-on-click-modal="type === 'view'"
    :disabled="type === 'view'"
    :class="type === 'view' ? 'viewForm' : ''"
    v-loading="loading"
  >
    <!-- <el-form-item label="平台" prop="uri">
      <el-radio-group v-model="ruleForm.platform">
        <el-radio :label="1">前端</el-radio>
        <el-radio :label="2">后端</el-radio>
      </el-radio-group>
    </el-form-item> -->
    <el-form-item label="类型" prop="uri">
      <el-radio-group v-model="ruleForm.type">
        <el-radio :label="2">菜单</el-radio>
        <el-radio :label="1">按钮</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="上级菜单" prop="parentId">
      <el-cascader
        v-model="ruleForm.parentId"
        :options="props.treeData"
        filterable
        clearable
        @change="handleChange"
        :props="propsTree"
      >
        <template #default="{ node, data }">
          <span>{{ data.title }}</span>
          <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
        </template>
      </el-cascader>
    </el-form-item>

    <el-form-item :label="isBtn ? '按钮名称' : '标题'" prop="title">
      <el-input v-model="ruleForm.title" />
    </el-form-item>

    <el-form-item v-if="isMene" :label="'组件别名'" prop="name">
      <el-input @blur="handleBlur" v-model="ruleForm.name" />
    </el-form-item>
    <el-form-item :label="isBtn ? '按钮标识' : '路由路径'" prop="path">
      <el-input
        :placeholder="isBtn ? '按钮标识' : '加/输入全路径，不加 由上级菜单拼接'"
        v-model="ruleForm.path"
      />
    </el-form-item>
    <el-form-item v-if="isMene" label="组件路径" prop="component">
      <el-input
        placeholder="例:system/admin | 相对于/views/的路径 "
        v-model="ruleForm.component"
      />
    </el-form-item>
    <el-form-item label="图标" v-if="isMene" prop="icon">
      <div class="icon-input">
        <ImageFileID
          style="margin-right: 10px"
          v-if="ruleForm.icon"
          :fileId="ruleForm.icon"
        />

        <el-input
          class="input"
          placeholder="管理端可选svg图标，用户端请上传文件"
          v-model="ruleForm.icon"
        >
          <template #append>
            <el-button @click="handleIcon" style="padding: 0 12px" :icon="Edit" />
          </template>
        </el-input>

        <el-button style="padding: 0 12px" :icon="Plus" @click="handleUploads">
          上传文件
        </el-button>
      </div>
    </el-form-item>
    <el-form-item label="排序" v-if="type === 'edit'" prop="sortNumber">
      <el-input-number v-model="ruleForm.sortNumber" :min="0" />
    </el-form-item>
    <el-form-item v-if="types === 100" label="跳转路由" prop="redirect">
      <el-input v-model="ruleForm.redirect" />
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="ruleForm.remark" />
    </el-form-item>
  </el-form>
  <div class="dialog-form-footer">
    <el-button @click="handleClose">关闭</el-button>
    <el-button type="primary" v-if="type !== 'view'" @click="submitForm">确定</el-button>
  </div>
  <Icons v-if="visibleIcon" @changeIcon="changeIcon" v-model="visibleIcon" />
</template>
<style lang="scss" scoped>
.icon-input {
  display: flex;
  flex: 1;
  align-items: center;
  .input {
    flex: 1;
  }
  .icon {
    font-size: 24px;
    margin-right: 10px;
  }
}
.dialog-form-footer {
  text-align: right;
  margin-top: 25px;
}
</style>
